<?php

namespace App\Models;

use Illuminate\Support\Str;
use App\Service\Base\Model;

class Admin extends Model
{

    // 用户管理
    protected $table = 'admin';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id'];

    // 获取所有的
    public function getAll($where = [])
    {
        $fields = $this->getTableField(true);
        $fields = array_diff($fields, ['role', 'password']);
        // 查询
        $lists = $this->where($where)->select($fields)->get()->toArray();
        $lists = array_column($lists, null, 'id');

        return $lists;
    }

    // 权限
    public function getRole()
    {
        $roles = [
            // 开始的两个栏目
            ['role' => 'admin', 'name' => '管理员管理',],
            //['role' => 'user', 'name' => '用户管理',],

            // 中间四个文章栏目
            /*['role' => 'news', 'channel' => 'news', 'name' => '新闻管理', 'child' => []],
            ['role' => 'video', 'channel' => 'video', 'name' => '视频管理',], // ?
            ['role' => 'plan', 'channel' => 'plan', 'name' => '蓝字计划',],  // ?
            ['role' => 'ship', 'channel' => 'ship', 'name' => '船涨管理',],  // ?*/

            // 草稿管理
            // ['role' => 'is_draft', 'name' => '草稿管理',],  // ?

            // 其他栏目
            //['role' => 'authors', 'name' => '专栏管理', 'child' => [['role' => 'author', 'name' => '专栏作家',], ['role' => 'author-article', 'name' => '文章管理',]]],
            //['role' => 'advertisement', 'name' => '广告管理', 'child' => [['role' => 'adv', 'name' => '广告位',], ['role' => 'adv-space', 'name' => '广告列表',]]],
            //['role' => 'topic', 'name' => '话题管理',],

            /*['role' => 'site', 'name' => '系统设置', 'child' => [['role' => 'setting', 'name' => '站点设置',]],],
            [
                'role'  => 'innerend',
                'name'  => '栏目设置',
                'child' => [
                    ['role' => 'news-cate', 'channel' => 'news', 'name' => '新闻',],
                    ['role' => 'video-cate', 'channel' => 'video', 'name' => '视频',],
                    //['role' => 'plan-cate', 'channel' => 'plan', 'name' => '蓝字计划',],
                    //['role' => 'ship-cate', 'channel' => 'ship', 'name' => '船涨管理',],
                ],
            ],*/
        ];

        // ['role' => 'innerend', 'name' => '左侧栏目管理', 'child' => [['role' => 'innerend.cate', 'name' => '栏目管理',], ['role' => 'innerend.site', 'name' => '系统设置',]]]
        //$isHead = ['role' => 'news.is_header', 'name' => '头条', 'is_header' => 1];

        // 获取栏目组装到分类下面
        /*$siteDb = new SiteInfo();
        $cateDb = new Cate();
        $cates  = $cateDb->isCache(true)->getAll(['status' => '1'], 'rank ASC');
        $sites  = $siteDb->isCache(true)->getAll(['status' => '1'], 'id DESC');

        // 组合权限
        foreach($roles as &$_role){
            $roleName = $_role['role'];
            // 组合权限：栏目
            if(in_array($roleName, ['news', 'video', 'plan', 'ship'])){
                $_child = $this->toTree($cates, $roleName);
                if($_child){
                    $_role['child'] = $_child;
                }

                // 增加头条
                *if($roleName == 'news'){
                    array_unshift($_role['child'], $isHead);
                }*
            }
            // 组合权限：系统设置
            if(in_array($roleName, ['site',])){
                foreach($sites as $_site){
                    if(empty($_site['key'])){
                        continue;
                    }
                    // role 是控制器加参数形式
                    $_role['child'][] = ['role' => 'site'.$_site['key'], 'name' => $_site['title'], 'key' => $_site['key'],];
                }
            }
            // 处理一下
            if(!empty($_role['child'])){
                $_role['child'] = array_values($_role['child']);
            }
        }*/

        return $roles;
    }

    // 检查权限
    public function checkRole($roles, $controller, $param)
    {
        // 基础：只有控制器的权限判断
        if(in_array($controller, $roles)){
            return true;
        }

        // 参数
        // 控制器与栏目id组合的权限 => news.1
        // 特殊权限 => news.is_header
        if(in_array($controller.'.'.$param, $roles)){
            return true;
        }

        return false;
    }

    // 检查唯一性
    public function checkUser($data, $id = '')
    {
        $where = [];
        // username 唯一性
        if(!empty($data['username'])){
            $yzwhere = [['username', '=', $data['username']]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->where($where)->where($yzwhere)->first();
            if($info){
                return $this->return_false('该用户名已经存在！');
            }
        }


        // email 唯一性
        if(!empty($data['email'])){
            $yzwhere = [['email', '=', $data['email']]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->where($where)->where($yzwhere)->first();
            if($info){
                return $this->return_false('该邮箱已经存在！');
            }
        }

        // mobile 唯一性
        if(!empty($data['mobile'])){
            $yzwhere = [['mobile', '=', $data['mobile']]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->where($where)->where($yzwhere)->first();
            if($info){
                return $this->return_false('该手机号已经存在！');
            }
        }

        // 整理角色
        if(empty($data['role'])){
            unset($data['role']);
        } else{
            if(is_string($data['role'])){
                return $this->return_false('权限为数组！');
            }

            // 整理
            $roles = [];
            foreach($data['role'] as $_role){
                if(empty($_role['role'])){
                    continue;
                }
                $roles[] = $_role['role'];
            }
            $data['role'] = json_encode($roles, 1);
        }

        return $data;
    }

    // 添加验证
    public function checkData($data, $where = [])
    {
        // 随机码
        // 修改的时候，没有传递密码 则不修改密码
        if($where && empty($data['password'])){
            unset($data['password']);
        } else{
            // 不是修改的时候 没有传递密码，默认为123456
            $salt = Str::random(4);
            if(empty($data['password'])){
                $data['password'] = 123456;
            }

            // 密码
            $data['salt']     = $salt;
            $data['password'] = $this->add_md5($data['password'], $salt);
        }

        return $data;
    }

    // 登录
    public function login($username, $password)
    {
        // 获取用户信息
        $field = ['id', 'username', 'password', 'salt', 'status', 'role', 'mobile', 'nickname',];
        $info  = $this->where(['username' => $username])->select($field)->first(); // ->recycle()
        if(empty($info)){
            return $this->return_false('用户不存在！！');
        }
        if($info->status === 0){
            return $this->return_false('用户被禁止登录！！');
        }

        // 验证密码
        $isCheck = $this->ckeckPassword($password, $info->salt, $info['password']);
        if(!$isCheck){
            return $this->return_false('密码错误！！');
        }

        $role = $info->role;
        if(is_string($info->role)){
            $role = json_decode($info->role);
        }
        // 为了避免前端页面爆粗
        if(empty($role)){
            $role = ['admin'];
        }

        // 登录成功
        $user = ['id' => $info->id, 'username' => $info->username, 'mobile' => $info->mobile, 'role' => $role, 'ctime' => LARAVEL_TIME];

        /*$onlineip = request()->ip();
        $updata   = ['last_ip' => $onlineip, 'last_time' => time(),];
        DB::startTrans();
        try{
            $rst = $this->where('id', $info->id)->save($updata);
            // 提交事务
            DB::commit();
        } catch(\Exception $e){
            // 回滚事务
            DB::rollback();
            return $this->return_false($this->getError(), 5000);
        }*/

        return $user;
    }

    // 加密密码
    public function add_md5($password, $salt = '')
    {
        return password_hash($password.$salt, PASSWORD_DEFAULT);
    }

    // 解密
    public function ckeckPassword($password, $salt, $hash)
    {
        return password_verify($password.$salt, $hash);
    }

    // 整理组合拥有的权限
    // 是否需要展示父级（用于查看的时候不需要展示父级）
    public function makeRoles($roles, $is_parent = true, $isInnerend = 0)
    {
        $all    = $this->getRole();
        $result = $this->showTree($all, $roles, $is_parent);
        // 用户id为1 才有的后台栏目管理
        // 用户id为1 不会有任何权限判断
        /*if($isInnerend){
            $result[] = ['role' => 'innerend', 'name' => '左侧栏目开关', 'child' => [['role' => 'cate', 'name' => '栏目管理',], ['role' => 'siteinfo', 'name' => '系统设置',]]];
        }*/

        return $result;
    }

    // 生成树状
    public function toTree($data = [], $channel = 'news', $myid = 0, $limitLevel = 0, $currentLevel = 0)
    {
        $trees = [];
        $data  = array_values($data);
        foreach($data as $key => $val){
            // 不是这个分类的 不能使用
            if($val['channel'] != $channel){
                continue;
            }

            if($val['pid'] == $myid){
                if($limitLevel > 0 && $limitLevel == $currentLevel){
                    return $trees;
                }

                $item = [];
                // 组合
                $item['role']    = $channel.'.'.$val['id'];
                $item['cate_id'] = $val['id'];
                $item['id']      = $val['id'];
                $item['pid']     = $val['pid'];
                $item['name']    = $val['name'];
                $item['channel'] = $channel;

                unset($data[$key]);

                $children = $this->toTree($data, $channel, $val['id'], $limitLevel, ($currentLevel + 1));
                if(!empty($children)){
                    //$val['child']  = $children;
                    $item['child'] = $children;
                }
                $trees[] = $item;
            }
        }

        return $trees;
    }

    // 获取树状 展示
    public function showTree($tree, $roles, $is_parent = true)
    {
        $result = [];
        foreach($tree as $item){
            if(in_array($item['role'], $roles)){
                $result[] = $item;
                continue;
            }
            // 如果有子级
            if(!empty($item['child'])){
                $result2 = $this->showTree($item['child'], $roles, $is_parent);
                // 如果选中子级栏目
                if($result2){
                    if($is_parent){
                        // 展示父级
                        $result[] = ['role' => $item['role'], 'name' => $item['name'], 'channel' => $item['channel'] ?? '', 'child' => $result2];
                    } else{
                        // 不展示父级
                        $result = empty($result) ? $result2 : array_merge($result, $result2);
                    }
                }
            }
        }

        return $result;
    }

    // 定义验证操作
    public function rules()
    {

        $add = [
            'username' => 'required',
            'salt'     => 'required',
        ];

        $edit = [
        ];

        $info = [
            'password' => ['max:129'],
            'is_del'   => ['in:0,1,2'],
            //'role'     => ['in:0,1,2'],
        ];

        $rule = [
            //'nickname' => 'required',
            //'role'       => ['required'],
            //'article_no' =>['numeric'],
            //'mobile'     =>['required'],
            'password' => ['max:65'],
            'role'     => ['in:0,1,2'],
            'status'   => ['in:0,1,2'],
        ];


        $msg = [
            //'mobile'     => '手机号',
            //'article_no' => '创建文章数',
            'id'       => '编号',
            'username' => '用户名',
            'password' => '密码',
            'nickname' => '昵称',
            'role'     => '角色',
            'salt'     => '随机码',
            'status'   => '状态',
            'power'    => '权限',
            'ctime'    => '创建时间',
            'mtime'    => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add, 'info' => $info];
    }
}
